package cn.lexi.vip.exception;

import cn.lexi.vip.controller.IBaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


/**
 * Created by Miraculous on 15/7/21.
 */
@Component
@Qualifier("exceptionLogger")
public class ExceptionLogger implements IBaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionLogger.class);

    @Value("${lexi.exception.maxLogStackTrace}")
    private Integer maxLogStackTrace;

    @Value("${lexi.exception.debug}")
    private Boolean isDebug;

    private ExceptionLoggingStrategy loggingStrategy;

    @PostConstruct
    private void init() {
        loggingStrategy = new ExceptionLoggingStrategy() {
            @Override
            public void logException(Logger logger, Throwable e) {
                logger.error("error " + getRequestUri(), e);
            }

            @Override
            public void warnException(Logger logger, Throwable e) {
                logger.warn("warn " + getRequestUri(), e);
            }

            private String getRequestUri () {
                try {
                    return getRequest().getRequestURI();
                } catch (Exception ex) {
                    return "";
                }
            }
        };
    }

    public void warnException(Throwable e) {
        loggingStrategy.warnException(LOGGER, e);
    }

    public void warnException(Logger logger, Throwable e) {
        loggingStrategy.warnException(logger, e);
    }

    public void logException(Throwable e) {
        loggingStrategy.logException(LOGGER, e);
    }

    public void logException(Logger logger, Throwable e) {
        loggingStrategy.logException(logger, e);
    }

    public interface ExceptionLoggingStrategy {
        void logException(Logger logger, Throwable e);

        void warnException (Logger logger, Throwable e);
    }
}
